import store from '@/store'
import pageConfig from '@/config'
import { getToken, removeToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { toast, showConfirm, tansParams } from '@/utils/common'

let timeout = 10000
const baseUrl = pageConfig.baseUrl

/*
  接口处理函数
*/
function apiAxios(method, url, params, requestConfig) {
  const config = { method, url, params, ...requestConfig }
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  config.header = config.header || {}
  if (getToken() && !isToken) {
    config.header['Authorization'] = 'Bearer ' + getToken()
  }
  // get请求映射params参数
  if (method === 'get' || (method === 'put' && requestConfig.lickGet)) {
    let requestUrl = url + '?' + tansParams(params)
    config.url = requestUrl
  }
  let requestParams = {}
  for (let key in config.params) {
    if (config.params[key] !== null) {
      requestParams[key] = config.params[key]
    }
  }
  return new Promise((resolve, reject) => {
    uni.request({
      method: method || 'get',
      timeout: config.timeout ||  timeout,
      url: config.baseUrl || baseUrl + config.url,
      params: requestParams,
      data: requestParams,
      header: config.header,
      dataType: 'json'
    }).then(response => {
      let [error, res] = response
      if (error) {
        toast('后端接口连接异常')
        reject('后端接口连接异常')
        return
      }
      const code = res.data.code || 200
      const msg = errorCode[code] || res.data.msg || errorCode['default']
      if (code === 401) {
        showConfirm('登录状态已过期，您可以继续留在该页面，或者重新登录?').then(res => {
          if (res.confirm) {
            removeToken()
            // uni.reLaunch({ url: '/subPages/home/login' })
          }
        })
        reject('无效的会话，或者会话已过期，请重新登录。')
      } else if (code === 500) {
        toast(msg)
        reject('500')
      } else if (code !== 200) {
        toast(msg)
        reject(code)
      }
      resolve(res.data)
    })
    .catch(error => {
      let { message } = error
      if (message === 'Network Error') {
        message = '后端接口连接异常'
      } else if (message.includes('timeout')) {
        message = '系统接口请求超时'
      } else if (message.includes('Request failed with status code')) {
        message = '系统接口' + message.substr(message.length - 3) + '异常'
      }
      toast(message)
      reject(error)
    })
  })
}

// 返回在vue模板中的调用接口
export default {
  get: function (url, params = {}, requestConfig = {}) {
    return apiAxios('get', url, params, requestConfig)
  },
  post: function (url, params = {}, requestConfig = {}) {
    return apiAxios('post', url, params, requestConfig)
  },
  put: function (url, params = {}, requestConfig = {}) {
    return apiAxios('put', url, params, requestConfig)
  },
  delete: function (url, params = {}, requestConfig = {}) {
    return apiAxios('delete', url, params, requestConfig)
  },
  file: function (url, params = {}, requestConfig = {}) {
    return apiAxios('file', url, params, requestConfig)
  }
}
